package com.swd.order.controller;

import com.swd.order.model.User;
import com.swd.order.service.UserService;
import com.swd.order.service.WxService;
import com.swd.order.util.JwtUtil;
import com.swd.order.vo.Ret;
import com.swd.order.vo.Rets;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.MalformedInputException;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private WxService wxService;
    @Autowired
    private UserService userService;


    @PostMapping("login")
    private Ret login(String code){
        log.info("用户登入{}",code);
        if (StringUtils.isEmpty(code)){
            return Rets.failure("code不能为空");
        }
        String openId = wxService.getOpenId(code);
        User user = userService.getUserByOpenId(openId);
        if (user == null){
            log.info("未注册用户{}",openId);
            return Rets.noReg(openId);
        }
        log.info("用户登入{}",user);
        return Rets.success(user);
    }

    @PostMapping("register")
    private Ret register(User user){

        if (StringUtils.isEmpty(user.getWxName())||StringUtils.isEmpty(user.getOpenid())){
            return Rets.failure("微信信息不能为空");
        }

        User register = userService.register(user.getOpenid(), user.getWxName(), user.getPicture());

        if (register == null){
            return Rets.failure("注册失败");
        }

        return Rets.success(user);
    }

    @PostMapping("admin/login")
    public Ret adminLogin(String userName , String password){

        if (!("admin".equals(userName) && "password".equals(password))){
            return Rets.failure("帐号或密码错误");
        }

//        userService.

        return Rets.success();
    }

    @GetMapping("all")
    public Ret all(){
        return  Rets.success(userService.queryAll());
    }

    @PostMapping("update")
    public Ret update(@RequestBody User user){

        if (user.getId() == null){
            return Rets.failure("用户不存在");
        }

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setName(user.getName());
        updateUser.setOrderNotify(user.getOrderNotify());
        updateUser.setMealNotify(user.getMealNotify());
        updateUser.setAdminister(user.getAdminister());


        boolean success = userService.update(updateUser);
        if (success){
            return Rets.success();
        }else {
            return Rets.failure("修改失败");
        }
    }

}
